package org.darcy.youchat.activity.me.myinfo;

import android.os.Environment;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bm.library.PhotoView;
import org.darcy.youchat.R;
import org.darcy.youchat.activity.BaseActivity;
import org.darcy.youchat.databinding.ActivityShowBigImageBinding;
import org.darcy.youchat.factory.PopupWindowFactory;
import org.darcy.youchat.imageloader.MyImageLoader;
import org.darcy.youchat.utils.UIUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 查看头像
 */
public class ShowBigImageActivity extends BaseActivity {

    private ActivityShowBigImageBinding binding;

    private String mUrl;
    PhotoView mPv;
    private FrameLayout mView;
    private PopupWindow mPopupWindow;

    @Override
    public void init() {
        mUrl = getIntent().getStringExtra("url");
    }

    @Override
    public void initView() {
        binding = ActivityShowBigImageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.mToolbar.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        binding.mToolbar.toolbar.setNavigationIcon(R.mipmap.ic_back);
        getSupportActionBar().setTitle("头像");

        mPv.enable();// 启用图片缩放功能
        MyImageLoader.LoadNetImage(mUrl, mPv);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.menu_more, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.itemMore:
                showPopupMenu();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void showPopupMenu() {
        if (mView == null) {
            mView = new FrameLayout(this);
            mView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mView.setBackgroundColor(UIUtils.getColor(R.color.white));

            TextView tv = new TextView(this);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, UIUtils.dip2Px(45));
            tv.setLayoutParams(params);
            tv.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
            tv.setPadding(UIUtils.dip2Px(20), 0, 0, 0);
            tv.setTextColor(UIUtils.getColor(R.color.gray0));
            tv.setTextSize(14);
            tv.setText("保存到手机");
            mView.addView(tv);

            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopupWindow.dismiss();
                    //下载头像
                    final String dirPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), getPackageName()).getAbsolutePath();
                    final String fileName = "header.jpg";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .get()
                            .url(mUrl)
                            .build();
                    Call call = okHttpClient.newCall(request);

                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            UIUtils.showToast("头像保存失败");
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws FileNotFoundException {
                            UIUtils.showToast("头像保存在" + dirPath + "/" + fileName);
                            //保存文件
                            InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
                            File target = new File(dirPath, fileName);
                            FileOutputStream fileOutputStream = new FileOutputStream(target);
                            try {
                                byte[] buffer = new byte[2048];
                                int len;
                                while ((len = inputStream.read(buffer)) != -1) {
                                    fileOutputStream.write(buffer, 0, len);
                                }
                                fileOutputStream.flush();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        }
        mPopupWindow = PopupWindowFactory.getPopupWindowAtLocation(mView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, getWindow().getDecorView().getRootView(), Gravity.BOTTOM, 0, 0);
        mPopupWindow.setOnDismissListener(() -> PopupWindowFactory.makeWindowLight(ShowBigImageActivity.this));
        PopupWindowFactory.makeWindowDark(this);
    }
}
